package com.codepilot.server.service.impl;

import com.codepilot.server.mapper.RecommendMapper;
import com.codepilot.server.model.dto.UserDTO;
import com.codepilot.server.model.entity.User;
import com.codepilot.server.model.exception.enums.GlobalErrorCodeConstants;
import com.codepilot.server.model.vo.CommonResult;
import com.codepilot.server.model.vo.RecommendListVO;
import com.codepilot.server.service.RecommendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class RecommendServiceImpl implements RecommendService {

    @Autowired
    private RecommendMapper recommendMapper;

    @Override
    public CommonResult<RecommendListVO> getRecommends(String type) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDTO loginUser = (UserDTO) authentication.getPrincipal();
        User user = loginUser.getUser();
        try {
            List<Integer> problems = new ArrayList<>();
            Random random = new Random();
            if (type.equals("customized")) {
                problems = recommendMapper.selectCustomizedRecommends(user.getId());
            } else if (type.equals("classified")) {
                problems = recommendMapper.selectClassifiedRecommends(user.getId());
            } else if (type.equals("challenging")) {
                problems = recommendMapper.selectCustomizedRecommends(random.nextInt(199)+1);
            } else if (type.equals("hot")) {
                problems = recommendMapper.selectHotRecommends(user.getId());
            } else if (type.equals("plan")) {
                problems = recommendMapper.selectCustomizedRecommends(random.nextInt(199)+1);
            }
            RecommendListVO recommends = RecommendListVO.builder()
                    .source("OJ")
                    .problemList(problems).build();
            return CommonResult.success(recommends);
        } catch (Exception e) {
            return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR);
        }
    }

}
